<template>
  <el-row :gutter="20">
    <el-col :span="24">
      <el-card class="book-card">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button type="success" plain @click="insertBookshow = true;">新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="exp">导出表</el-button>
          </el-form-item>

          <el-upload action="http://localhost:8080/admin/book/pxe" style="display: inline-block; margin-left: 10px"
          :show-file-list=false :on-success="successUpload">
            <el-button  type="primary">
              导入表
            </el-button>
          </el-upload>

          <el-form-item style="float: right;">
            <el-input v-model="bname" placeholder="请输入要搜索的书名" @input="selectByPage(1)" />
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="bauthor" placeholder="请输入要搜索的作者" @input="selectByPage(1)" />
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="pageInfo.list" border style="width: 100%">
          <el-table-column fixed prop="bid" label="书籍ID" width="100" />
          <el-table-column fixed prop="bavatar" label="书籍图像" width="100">
            <template #default="scope">
              <el-avatar shape="square" :size="50" :src="'http://localhost:8080/upload/' + scope.row.bavatar" />
            </template>
          </el-table-column>
          <el-table-column prop="bname" label="书名" width="180" />
          <el-table-column prop="bauthor" label="作者" width="100" />
          <el-table-column prop="bpress" label="出版社" width="140" />
          <el-table-column prop="bdate" label="出版日期" width="110" />
          <el-table-column prop="bnumber" label="书籍数量" width="100" />
          <el-table-column prop="classify.cid" label="分类ID" width="100" />
          <el-table-column prop="classify.cname" label="分类" width="100" />
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button size="small" type="primary" @click="showUpdateUser(scope.row.bid)">
                <el-icon>
                  <Edit />
                </el-icon>修改
              </el-button>
              <el-popconfirm title="你确定要删除该书籍吗?" confirm-button-text="确认" cancel-button-text="取消" width="200px"
                @confirm="deleteBook(scope.row.bid)">
                <template #reference>
                  <el-button size="small" type="danger">
                    <el-icon>
                      <Delete />
                    </el-icon>删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-row class="row-bg" justify="center">
          <el-pagination style="margin-top: 20px;" background layout="prev, pager, next"
            v-model:current-page="pageInfo.pageNum" :page-count="pageInfo.pages" @update:current-page="selectByPage" />
        </el-row>

      </el-card>
    </el-col>
  </el-row>

  <!-- 添加书籍对话框开始 -->
  <el-dialog v-model="insertBookshow" title="添加书籍" width="500" class="add-book-dialog" :close-on-click-modal="false">
    <el-form>
      <el-form-item label="书名" label-width="20%">
        <el-input v-model="bookAdd.bname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="作者" label-width="20%">
        <el-input v-model="bookAdd.bauthor" autocomplete="off" />
      </el-form-item>

      <el-form-item label="出版社" label-width="20%">
        <el-input v-model="bookAdd.bpress" autocomplete="off" />
      </el-form-item>

      <el-form-item label="出版日期" label-width="20%">
        <el-input v-model="bookAdd.bdate" autocomplete="off" />
      </el-form-item>

      <el-form-item label="数量" label-width="20%">
        <el-input v-model="bookAdd.bnumber" autocomplete="off" />
      </el-form-item>

      <el-form-item label="分类ID" label-width="20%">
        <el-input v-model="bookAdd.cid" autocomplete="off" />
      </el-form-item>

      <el-form-item label="头像" label-width="20%">
        <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload/" name="pic" :headers="headers"
          :show-file-list="false" :on-success="handleAvatarSuccessAdd" :before-upload="beforeAvatarUploadAdd">
          <img v-if="imageUrlAdd" :src="imageUrlAdd" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="insertBookRemove">取消</el-button>
        <el-button type="primary" @click="addBook()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--添加书籍的对话框结束-->

  <!-- 修改书籍对话框开始 -->
  <el-dialog v-model="updateBookShow" title="修改书籍" width="500" class="update-book-dialog" :close-on-click-modal="false">
    <el-form>
      <el-form-item label="书名" label-width="20%">
        <el-input v-model="bookUpdate.bname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="作者" label-width="20%">
        <el-input v-model="bookUpdate.bauthor" autocomplete="off" />
      </el-form-item>

      <el-form-item label="出版社" label-width="20%">
        <el-input v-model="bookUpdate.bpress" autocomplete="off" />
      </el-form-item>

      <el-form-item label="出版日期" label-width="20%">
        <el-input v-model="bookUpdate.bdate" autocomplete="off" />
      </el-form-item>

      <el-form-item label="数量" label-width="20%">
        <el-input v-model="bookUpdate.bnumber" autocomplete="off" />
      </el-form-item>

      <el-form-item label="分类ID" label-width="20%">
        <el-input v-model="bookUpdate.cid" autocomplete="off" />
      </el-form-item>

      <el-form-item label="头像" label-width="20%">
        <el-upload class="avatar-uploader" action="http://localhost:8080/admin/upload/" name="pic" :headers="headers"
          :show-file-list="false" :on-success="handleAvatarSuccessUpdate" :before-upload="beforeAvatarUploadUpdate">
          <img v-if="imageUrlUpdate" :src="imageUrlUpdate" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateBookRemove">取消</el-button>
        <el-button type="primary" @click="updateBook()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--修改书籍的对话框结束-->

</template>

<script setup>
import { onMounted } from 'vue';
import { reactive, ref, computed } from 'vue';
import { ElLoading } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import bookApi from '@/api/bookApi';
import axios from 'axios';
import * as XLSX from 'xlsx'; // 使用 SheetJS 库进行 Excel 导出
import { useTokenStore } from '@/stores/token';

// const headers = reactive({
//     token: sessionStorage.getItem('token');
// });

const tokenStore = useTokenStore();

//计算属性
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
});

//用来搜索书名关键字
const bname = ref('');

const bauthor = ref('');

// 获取书籍
// const bookList = ref([]);

//新增 上传图片之前的回调
function beforeAvatarUploadAdd(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M');
    return false
  }
  return true;
}

//修改 上传图片之前的回调
function beforeAvatarUploadUpdate(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M');
    return false
  }
  return true;
}

//新增 上传图片的地址
const imageUrlAdd = ref("");

//修改 上传图片的地址
const imageUrlUpdate = ref("");

//新增 成功上传之后的回调
function handleAvatarSuccessAdd(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    imageUrlAdd.value = "http://localhost:8080/upload/" + resp.data;
    bookAdd.value.bavatar = resp.data;
  }
}

//修改 成功上传之后的回调
function handleAvatarSuccessUpdate(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    imageUrlUpdate.value = "http://localhost:8080/upload/" + resp.data;
    bookUpdate.value.bavatar = resp.data;
  }
}


// 定义方法存储书籍信息
const bookAdd = ref({
  bavatar: '',
  bname: '',
  bauthor: '',
  bpress: '',
  bdate: '',
  bnumber: '',
  cid: ''
});

// 定义方法存储修改书籍信息
const bookUpdate = ref({
  bavatar: '',
  bname: '',
  bauthor: '',
  bpress: '',
  bdate: '',
  bnumber: '',
  cid: ''
});



// 新增对话框是否显示
const insertBookshow = ref(false);

// 修改对话框是否显示
const updateBookShow = ref(false);

// 定义方法完成书籍的添加
function addBook() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  bookApi.insertBook(bookAdd.value)
    .then(resp => {
      loading.close();
      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 隐藏对话框
        insertBookshow.value = false;
        // 清空对话框中的数据
        bookAdd.bavatar = '',
          bookAdd.bname = '';
        bookAdd.bauthor = '';
        bookAdd.bpress = '';
        bookAdd.bdate = '';
        bookAdd.bnumber = '';
        bookAdd.cid = '';
        //imgUrl清空
        imageUrlAdd.value = "";
        // 刷新表格数据
        selectByPage(1);
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    })
}

// 定义方法完成书籍的修改
function updateBook() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  bookApi.updateBook(bookUpdate.value)
    .then(resp => {
      loading.close();
      if (resp.code === 10000) {
        // 弹出成功消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 隐藏对话框
        updateBookShow.value = false;
        // 刷新表格数据
        selectByPage(1);
      } else {
        // 弹出错误消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    })
}

// 在修改中查询所有书籍
function showUpdateUser(bid) {
  bookApi.selectBuBid(bid)
    .then(resp => {
      bookUpdate.value = resp.data;
      updateBookShow.value = true;
      imageUrlUpdate.value = `http://localhost:8080/upload/${bookUpdate.value.bavatar}`;
    });
}

// 表格加载开启
const loading = ref(true)

// 保存分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});

// 分页查询
function selectByPage(pageNum) {
  // 表格加载关闭
  loading.value = false;
  bookApi.selectByPage(pageNum, bname.value, bauthor.value)
    .then(resp => {
      pageInfo.value = resp.data;
    })
}

// 刷新页面
function refreshCurrentPage() {
  const urlParams = new URLSearchParams(window.location.search);
  const currentPage = parseInt(urlParams.get('page')) || 1;
  location.reload();
}

// 定义方法根据书籍id进行删除
function deleteBook(bid) {
  bookApi.deleteBook(bid)
    .then(resp => {
      // 判断 - 弹出消息 - 刷新表格
      if (resp.code == 10000) {
        // 弹出消息
        ElMessage({
          message: resp.msg,
          type: 'success',
          duration: 1200
        });
        // 刷新表格数据
        selectByPage(1);
      } else {
        // 弹出消息
        ElMessage({
          message: resp.msg,
          type: 'error',
          duration: 2000
        });
      }
    });
}

function successUpload(res){
  refreshCurrentPage();
}


function exp() {
    axios.get('http://localhost:8080/admin/book/exp', {
        responseType: 'blob' // 设置响应类型为 blob
    })
       .then(response => {
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'book.xlsx';
            a.click();
            window.URL.revokeObjectURL(url);
        })
       .catch(error => {
            console.error("导出报表出错: ", error);
            ElMessage.error('导出报表失败，请稍后重试');
        });
}

// 修改书籍对话框,点击取消按钮后清空数据
function updateBookRemove() {
  updateBookShow.value = false;
  bookUpdate.value.bavatar = '',
    bookUpdate.value.bname = '';
  bookUpdate.value.bauthor = '';
  bookUpdate.value.bpress = '';
  bookUpdate.value.bdate = '';
  bookUpdate.value.bnumber = '';
  bookUpdate.value.cid = '';
}

// 新增书籍对话框,点击取消按钮后清空数据
function insertBookRemove() {
  insertBookshow.value = false;
  bookAdd.value.bavatar = '',
    bookAdd.value.bname = '';
  bookAdd.value.bauthor = '';
  bookAdd.value.bpress = '';
  bookAdd.value.bdate = '';
  bookAdd.value.bnumber = '';
  bookAdd.value.cid = '';
}

// 默认查询第一页
selectByPage(1);
// 查询所有书籍
// selectAllBook();
</script>

<style scoped>
.book-card {
  border: 1px solid #d3d3d3;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
}

.book-table {
  background-color: #fff;
}

.book-table th {
  background-color: #e0e0e0;
  color: #333;
}

.add-book-dialog,
.update-book-dialog {
  border: 2px solid #666;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.dialog-footer button {
  margin-right: 10px;
  border-radius: 5px;
  padding: 5px 15px;
}

.dialog-footer button:hover {
  opacity: 0.8;
}

.el-pagination {
  background-color: #f9f9f9;
}

.el-dialog__header {
  background-color: #666;
  color: white;
  padding: 10px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  background-color: #f0f0f0;
}

.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>